package day03;

import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import untils.UserBehavior;
import untils.itemViewCountPerWindow;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

/**
 * 实现全窗口聚合函数
 */
public class Example7 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .readTextFile("D:\\atguigu\\flinkdata\\src\\main\\resources\\UserBehavior.csv")
                .map(new MapFunction<String, UserBehavior>() {
                    @Override
                    public UserBehavior map(String s) throws Exception {
                        String[] arr = s.split(",");
                        return new UserBehavior(
                                arr[0],arr[1],arr[2],arr[3],Long.parseLong(arr[4]) * 1000L
                        );
                    }
                })
                //筛选浏览的窗口
                .filter(r -> r.type.equals("pv"))
                //指定时间戳
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<UserBehavior>forBoundedOutOfOrderness(Duration.ofSeconds(0))
                                .withTimestampAssigner(new SerializableTimestampAssigner<UserBehavior>() {
                                    @Override
                                    public long extractTimestamp(UserBehavior userBehavior, long l) {
                                        return userBehavior.ts;
                                    }
                                })
                )
                //按照用户ID进行分区
                .keyBy(r -> r.userId)
                //每隔5分钟开启一个持续一小时的窗口
                .process(new FakeSlidingWindow(60 * 60 * 1000 , 5 * 60 * 1000L))
                .print();
        env.execute();
    }

    public static class FakeSlidingWindow extends KeyedProcessFunction<String,UserBehavior,itemViewCountPerWindow>{

        private long windowSize;//窗口长度
        private long windowStep;//滑动距离

        public FakeSlidingWindow(long windowSize, long windowStep) {
            this.windowSize = windowSize;
            this.windowStep = windowStep;
        }

        //保存每个窗口的所有数据 K -> 窗口时间 V -> 所有数据的List集合
        private MapState<Long, List<UserBehavior>> mapState;

        @Override
        public void open(Configuration parameters) throws Exception {
            mapState = getRuntimeContext().getMapState(
                    new MapStateDescriptor<Long, List<UserBehavior>>(
                            "window",
                            Types.LONG,
                            Types.LIST(Types.POJO(UserBehavior.class))
                    )
            );
        }

        @Override
        public void processElement(UserBehavior value, Context ctx, Collector<itemViewCountPerWindow> out) throws Exception {
            ArrayList<Long> windowStartTime = new ArrayList<>();
            //获取距离当前数据最近的窗口开始时间的时间戳
            long start = getWindowStart(value.ts,windowStep);
            //保存当前时间所在的所有窗口
            for (long i = start; i > value.ts - windowSize; i -= windowStep){
                windowStartTime.add(i);
            }

            //将当前数据给每个窗口保存一份
            for (Long i : windowStartTime){
                if (!mapState.contains(i)){//如果有没注册定时器的窗口
                    List<UserBehavior> element = new ArrayList<>();
                    mapState.put(i,element);
                } else {
                    List<UserBehavior> element = mapState.get(i);
                    element.add(value);
                    mapState.put(i,element);
                }
            }

            //注册当前数据所有的定时器
            for (long i :
                    windowStartTime) {
                ctx.timerService().registerEventTimeTimer(i + windowSize - 1L);
            }
        }

        @Override
        public void onTimer(long timestamp, OnTimerContext ctx, Collector<itemViewCountPerWindow> out) throws Exception {
            long windowStart = timestamp + 1L - windowSize;
            out.collect(
                    new itemViewCountPerWindow(
                            ctx.getCurrentKey(),
                            (long) mapState.get(windowStart).size(),
                            windowStart,
                            timestamp + 1L
                    )
            );

            mapState.remove(windowStart);
        }

        //根据事件时间计算所在窗口的开始时间
        public static long getWindowStart(long timestamp, long step) {
            return timestamp - (timestamp + step) % step;
        }
    }
}
